package belf.migrate.engine.admin.handler;

import belf.migrate.api.exception.CatalogException;
import belf.migrate.api.exception.DatabaseNotExistException;
import belf.migrate.api.table.schema.AbstractJdbcCatalog;
import belf.migrate.api.taskconf.ConnectionConf;
import belf.migrate.api.taskconf.DbObjectConf;
import belf.migrate.api.taskconf.SourceConf;
import belf.migrate.api.type.DbObjectType;
import belf.migrate.engine.job.CatalogCreator;
import belf.migrate.engine.job.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import spark.Request;
import spark.Response;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;

import static spark.Spark.post;

@Slf4j
public class ConnectorHandler {
    private static Gson gson = new Gson();

    public static void setupRoutes() {

        /*
          测试连接接口
         */
        post("/testConnect", ConnectorHandler::processTestConnection, gson::toJson);

    }

    private static JsonObject processTestConnection(Request request, Response response) {
        // 设置响应类型为JSON
        response.type("application/json");
        // 获取请求体中的JSON数据并反序列化为Job对象
        ObjectMapper mapper = new ObjectMapper();
        Connection connection = null;
        try {
            SourceConf sourceConf = mapper.readValue(request.body(), SourceConf.class);
            connection = DriverManager.getConnection(sourceConf.getConnectionConf().getUrl(), sourceConf.getConnectionConf().getUser(), sourceConf.getConnectionConf().getPassword());

            if (connection.isValid(5)) {
                return gson.toJsonTree(Result.success()).getAsJsonObject();
            } else {
                return gson.toJsonTree(Result.sqlFail("连接失效")).getAsJsonObject();
            }
        } catch (SQLException e) {
            log.error("连接失败", e);
            return gson.toJsonTree(Result.sqlFail(e.getMessage())).getAsJsonObject();
        } catch (JsonProcessingException e) {
            log.error("解析参数格式错误");
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.addProperty("code", 11);
            jsonResponse.addProperty("message", "解析请求的json格式失败");
            return jsonResponse;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    log.error("连接关闭失败");
                }
            }

        }
    }

}
